import React from 'react';
import { View, StyleSheet, Platform, Dimensions } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import DeviceInfo from 'react-native-device-info';

/**
 * 安全TabBar包装组件
 * 为内容区域提供底部边距，防止被自定义TabBar遮挡
 */
const TAB_BAR_HEIGHT = 60;
const EXTRA_THRESHOLD = 18; // 仅当检测到足够大的遮挡时才补偿

let cachedTabBarPadding = null;

const computeTabBarPadding = (insetBottom, brand = '', model = '') => {
  if (Platform.OS === 'ios') {
    return 0;
  }

  const normalizedBrand = brand.toLowerCase();
  const normalizedModel = model.toLowerCase();

  // 只对已知存在虚拟按键遮挡问题的品牌做特殊处理
  const problematicBrands = [
    'vivo',
    'iqoo',
    'oppo',
    'oneplus',
    'xiaomi',
    'redmi',
  ];
  const isProblematic = problematicBrands.some(
    keyword =>
      normalizedBrand.includes(keyword) || normalizedModel.includes(keyword),
  );

  // 三星和其他品牌跟iOS一样，不需要额外高度
  if (!isProblematic) {
    return 0;
  }

  const screenData = Dimensions.get('screen');
  const windowData = Dimensions.get('window');
  const navHeight = Math.max(0, screenData.height - windowData.height);
  const overlayExtra = Math.max(navHeight - insetBottom, 0);
  const needsExtra = overlayExtra > EXTRA_THRESHOLD;

  // 根据品牌设置不同的额外高度
  let brandBoost = 0;
  if (normalizedModel.includes('iqoo')) {
    brandBoost = 8;
  }

  if (!needsExtra) {
    return TAB_BAR_HEIGHT + insetBottom;
  }

  return TAB_BAR_HEIGHT + insetBottom + overlayExtra + brandBoost;
};

const SafeTabBarWrapper = ({ children, style, enableExtraPadding = true }) => {
  const insets = useSafeAreaInsets();
  const [tabBarPadding, setTabBarPadding] = React.useState(() => {
    if (!enableExtraPadding) {
      return 0;
    }
    if (cachedTabBarPadding !== null) {
      return cachedTabBarPadding;
    }
    return computeTabBarPadding(insets.bottom);
  });

  React.useEffect(() => {
    if (!enableExtraPadding) {
      setTabBarPadding(0);
      return;
    }

    if (Platform.OS === 'ios') {
      cachedTabBarPadding = 0;
      setTabBarPadding(0);
      return;
    }

    if (cachedTabBarPadding !== null) {
      setTabBarPadding(cachedTabBarPadding);
      return;
    }

    let isMounted = true;

    const fetchDeviceInfo = async () => {
      try {
        const brand = await DeviceInfo.getBrand();
        const model = await DeviceInfo.getModel();

        const padding = computeTabBarPadding(insets.bottom, brand, model);
        cachedTabBarPadding = padding;

        if (isMounted) {
          setTabBarPadding(padding);
        }
      } catch {
        const padding = computeTabBarPadding(insets.bottom);
        cachedTabBarPadding = padding;

        if (isMounted) {
          setTabBarPadding(padding);
        }
      }
    };

    fetchDeviceInfo();

    return () => {
      isMounted = false;
    };
  }, [enableExtraPadding, insets.bottom]);

  const paddingBottom = enableExtraPadding ? tabBarPadding : 0;

  return (
    <View style={[styles.container, { paddingBottom }, style]}>{children}</View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

export default SafeTabBarWrapper;
